<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\Cache;

/**
 * 阅读任务用户执行作品表
 * Class ArticleModel
 * @package app\common\model
 */
class ReadingTaskExecuteWorks extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'reading_task_execute_works';

    /**
     * 判断此作品是否阅读
     * @param user_id 用户id
     * @param task_id 任务id
     * @param database_id 数据库id
     * @param type 类型  1 作品  2 电子书
     * @param works_id 作品id
     * @param ebook_id 作品id
     */
    public function isReadingWorks($user_id, $task_id, $database_id, $type = 1, $works_id, $ebook_id)
    {
        return $this->where('user_id', $user_id)->where('task_id', $task_id)->where('database_id', $database_id)->where(function ($query) use ($type, $works_id, $ebook_id) {
            if ($type == 1) {
                $query->where('works_id', $works_id);
            } elseif ($type == 2) {
                $query->where('ebook_id', $ebook_id);
            }
        })->first();
    }

    /**
     * 判断此作品是否阅读
     * @param user_id 用户id
     * @param task_id 任务id
     * @param database_id 数据库id
     * @param type 类型  1 作品  2 电子书
     * @param works_id 作品id
     * @param ebook_id 作品id
     */
    public function addReadingWorks($user_id, $task_id, $database_id, $type, $works_id, $ebook_id)
    {
        $res = $this->isReadingWorks($user_id, $task_id, $database_id, $type, $works_id, $ebook_id);
        if ($res) {
            return false;
        }
        $this->task_id = $task_id;
        $this->user_id = $user_id;
        $this->database_id = $database_id;
        $this->type = $type;
        $this->works_id = $works_id;
        $this->ebook_id = $ebook_id;
        $this->save();
    }



    /**
     * 获取当前数据库作品阅读数据量
     * @param user_id 用户id
     * @param task_id 任务id
     * @param database_id 数据库id 没有数据库id，表示查询所有进度
     */
    public function readingWorksNumber($user_id, $task_id, $database_id = null)
    {
        return $this->where('user_id', $user_id)->where('task_id', $task_id)
            ->where(function ($query) use ($database_id) {
                if ($database_id) {
                    $database_id = !is_array($database_id) ? explode(',', $database_id) : $database_id;
                    $query->whereIn('database_id', $database_id);
                }
            })->count();
    }
}
